package com.example.book.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @Description
 * @ClassName BaseServlet
 * @Author 山山大魔王
 * @Date 2021/11/17 19:25
 * @Version 1.0
 */
public abstract class BaseServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        doPost(request,response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决post请求中文乱码问题
        //一定要在获取请求参数之间调用才有效
        request.setCharacterEncoding("utf-8");
        //解决响应的中文乱码
        response.setContentType("text/html; charset=UTF-8");

        String action = request.getParameter("action");
//        if ("regist".equals(action)){
//            regist(request,response);
//        }else if ("login".equals(action)){
//            login(request,response);
//        }
        try {
            //获取action业务鉴别字符串，获取相应的业务 方法反射对象
            Class<? extends BaseServlet> aClass = this.getClass();

            Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//            System.out.println(declaredMethod);
//            调用目标业务 方法
            declaredMethod.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);//把异常抛给Filter()
        }
    }


}
